package cn.seaboot.admin.mvc.utils;

import cn.seaboot.commons.core.FastJsonUtils;
import cn.seaboot.commons.digest.Base64;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 惯例设计工具，树状Map、对象组装
 *
 * @author CSS  2018-07-10 11:56
 */
public class CookiesUtil {

    private CookiesUtil() {
    }

    public static Cookie getCookieByName(HttpServletRequest request, String name) {
        if (request.getCookies() != null) {
            for (Cookie cookie : request.getCookies()) {
                if (cookie.getName().equals(name)) {
                    return cookie;
                }
            }
        }
        return null;
    }

    public static void clearCookie(HttpServletRequest request, HttpServletResponse response,
                                   String name) {
        Cookie cookie = getCookieByName(request, name);
        if (cookie == null) {
            return;
        }
        cookie.setValue("");
        cookie.setPath(request.getContextPath());
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

    /**
     * 按名获取cookie中的值
     */
    public static String getValueByName(HttpServletRequest request, String name) {
        Cookie cookie = getCookieByName(request, name);
        if (cookie == null) {
            return null;
        } else {
            return new String(Base64.decodeString(cookie.getValue()));
        }
    }

    /**
     * 按名获取cookie中的值，结果按照JSON解成对象
     */
    public static <T> T getValueByName(HttpServletRequest request, String name, Class<T> clazz) {
        String val = getValueByName(request, name);
        if (val == null) {
            return null;
        } else {
            return FastJsonUtils.parseObject(val, clazz);
        }
    }

    /**
     * 按名获取cookie中的值，结果按照JSON解成Map
     */
    public static Map<String, Object> getMapByName(HttpServletRequest request, String name) {
        String val = getValueByName(request, name);
        if (val == null) {
            return null;
        } else {
          return FastJsonUtils.toJSONObject(val);
        }
    }

    /**
     * 添加到cookie
     */
    public static void setCookie(
            HttpServletRequest request, HttpServletResponse response,
            String key, String value, int timeout) {
        Cookie cookie = new Cookie(key, Base64.encodeString(value.getBytes()));
        cookie.setPath(request.getContextPath());
        cookie.setMaxAge(timeout);
        response.addCookie(cookie);
    }

    /**
     * 添加到cookie，使用JSON编码
     */
    public static void setCookie(
            HttpServletRequest request, HttpServletResponse response,
            String key, Object value, int timeout) {
        setCookie(request, response, key, FastJsonUtils.toJSONString(value), timeout);
    }
}